package com.ewins.weatherdataclient.ui;

import com.ewins.weatherdataclient.interfacedatamodule.InterfaceDataManagerHttp;
import com.ewins.weatherdatautils.bean.DownLoadFile;
import com.ewins.weatherdatautils.bean.DownLoadFileInfo;
import com.ewins.weatherdatautils.bean.FileLoadChangedInfo;
import com.ewins.weatherdatautils.utils.Configuration;
import com.ewins.weatherdatautils.utils.SqliteAccess;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
import org.apache.log4j.Logger;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by hp on 2015/12/4.
 */
public class DownLoadMonitorFormHttp extends Stage {

    private static final String path = System.getProperty("user.dir");
    public EventBus eb=new EventBus();
    String dbFileName = Configuration.GetValueByKey(path + File.separator + "config" + File.separator + "config.properties", "DBFILENAME");

    List<DownLoadFileInfo> downLoadHistoryList = new ArrayList<DownLoadFileInfo>();     //下载历史
    SqliteAccess sqliteAccess;
    String root = System.getProperty("user.dir") + File.separator + "config" + File.separator + "config.properties";
    private static Logger logger = Logger.getLogger(DownLoadMonitorFormHttp.class);
    InterfaceDataManagerHttp loadServer = null;
    DownLoadFileInfo downLoadHistory;   //下载历史
    Timer tmr;
    DownLoadFile redownLoadFile;    //文件重新下载
    Label nowTime;      //当前时间
    TextArea textArea;
    Label taskNum;      //当前任务总数
    Label historyNum;   //下载历史总数
    Label networkStatus; //网络状态
    Label dlDestStatus; //下载目标目录状态
    BorderPane rootPane = new BorderPane();
    MenuItem menuItem;


    TabPane dlInfos=new TabPane();
    Tab currDL=new Tab("当前下载");
    Tab hisDL=new Tab("历史下载");

    TableView<DownLoadFileInfo> currTableView;      //当前下载文件列表
    TableView<DownLoadFileInfo> hisTableView;       //历史下载文件列表
    DateTimeFormatter dtf= DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter dtfr= DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
    List<TableView> tableViewList=new ArrayList<TableView>();      //table列表
    List<String> tabTypeList=new ArrayList<String>();   //过滤规则列表
    List<Tab> tabList=new ArrayList<Tab>();
    List<DownLoadFileInfo> dlist=new ArrayList<DownLoadFileInfo>();

    public DownLoadMonitorFormHttp() {

        eb.register(this);
        init();
        Platform.runLater(new Runnable() {
            public void run() {
                updateTime();           //更新当前时间
            }
        });
        updateNetwork(eb);        //定时更新网络状态
        searchHistory(eb);        //定查询历史下载列表

    }

    private void init() {

        setTitle("数据下载监控");
        setWidth(1500);
        setHeight(800);
        initView();
        Scene scene = new Scene(new Group(), this.getWidth(), this.getHeight());
        scene.setRoot(rootPane);
        setScene(scene);

        this.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent windowEvent) {
                windowEvent.consume();
                final OptionDialog optionDialog = new OptionDialog(DownLoadMonitorFormHttp.this);

                //关闭系统界面
                optionDialog.btnOk.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        if (loadServer != null) {
                            close();
                            loadServer.stopServer();
                            System.exit(0);
                        }
                    }
                });

                //对话框取消
                optionDialog.btnCancel.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        optionDialog.close();
                    }
                });

            }
        });
        //下载历史列表监听
        hisTableView.setRowFactory(new Callback<TableView<DownLoadFileInfo>, TableRow<DownLoadFileInfo>>() {
            @Override
            public TableRow<DownLoadFileInfo> call(TableView<DownLoadFileInfo> param) {
                return new TableRowControl();
            }
        });
        this.setResizable(false);

    }

    class TableRowControl extends TableRow<DownLoadFileInfo> {
        public TableRowControl() {
            super();
            this.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent event) {
                    if (TableRowControl.this.getIndex() < hisTableView.getItems().size())
                        if (event.getButton().equals(MouseButton.SECONDARY) && event.getClickCount() == 1) {
                            //doSomething
                            final OptionDialogDownload downloadDialog = new OptionDialogDownload(DownLoadMonitorFormHttp.this);

                            //重新下载
                            downloadDialog.btnOk.setOnAction(new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent event) {
                                    int i=TableRowControl.this.getIndex();
                                    redownLoadFile=new DownLoadFile();
                                    String fileName=hisTableView.getItems().get(i).getFileName();
                                    redownLoadFile.setName(fileName);
                                    redownLoadFile.setPrior(String.valueOf(hisTableView.getItems().get(i).getFilePriority()));
                                    redownLoadFile.setDatetime(hisTableView.getItems().get(i).getCreatedTimeDesc().replaceAll("/", "-"));
                                    String categoryName=hisTableView.getItems().get(i).getCategoryName();

                                    String path=hisTableView.getItems().get(i).getUrl();
                                    path=path.replaceAll(fileName,"");
                                    path=path.replaceAll(Configuration.GetValueByKey(root, "DownLoadFileUrl"),"");

                                    redownLoadFile.setPath(path);
                                    InterfaceDataManagerHttp.addRedownloadFile(redownLoadFile,categoryName);
                                    downloadDialog.close();
                                    textArea.appendText(getTime()+" 重新下载文件:"+fileName);
                                }
                            });

                            //重新下载取消
                            downloadDialog.btnCancel.setOnAction(new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent event) {
                                    downloadDialog.close();
                                }
                            });


                        }
                }
            });
        }
    }


    public void setLoadServer(InterfaceDataManagerHttp interfaceDataManager){

        this.loadServer=interfaceDataManager;
        loadServer.setOnChangedInfo(new FileLoadChangedInfo() {

            //正在下载列表
            @Override
            public void changed(final Collection<DownLoadFileInfo> fileInfo,final boolean isOpenNewTab, final String tabType) {
                Platform.runLater(new Runnable() {
                    public void run() {
                        //currTableView.getItems().clear();
                        //currTableView.getItems().addAll(fileInfo);
                        taskNum.setText("等待下载 : " + fileInfo.size());
                        textArea.setText("");
                        try {
                            for (DownLoadFileInfo downLoadFileInfo : fileInfo) {
                                if(null!=fileInfo)
                                textArea.appendText(getTime() + " : 文件 " + downLoadFileInfo.getFileName() + "  " + downLoadFileInfo.getStateDesc() + "\r\n");
                            }
                        } catch (ConcurrentModificationException e) {
                            //e.printStackTrace();
                        }

                        //新建下载标签页
                        if(isOpenNewTab) {
                            if (fileInfo.size()>0|fileInfo.size()==0) {
                                //总文件列表
                                ArrayList<DownLoadFileInfo> fileInfoList = (ArrayList<DownLoadFileInfo>) fileInfo;

                                TableView<DownLoadFileInfo> tableView = new TableView();
                                tableView.setEditable(true);
                                tableView.getColumns().addAll(
                                        getTableColumn("文件类型", "categoryName", 100),
                                        getTableColumn("文件名称", "fileName", 190),
                                        getTableColumn("优先级", "filePriority", 100),
                                        getTableColumnProperty("下载状态", "stateDescP", 150),
                                        getTableColumnProperty("下载进度", "loadProgressP", 150),
                                        getTableColumn("生成时间", "createdTimeDesc", 150),
                                        getTableColumnProperty("开始时间", "startTimeP", 150),
                                        getTableColumn("下载路径", "url", 400),
                                        getTableColumnProperty("备注", "errorDescP", 100));

                                Tab tab = new Tab("下载任务");
                                tab.setClosable(false);
                                dlInfos.getTabs().add(tab);
                                tab.setContent(tableView);
                                tab.isSelected();
                                tabList.add(tab);
                                tableViewList.add(tableView);       //tableView列表

                                if (null != tabType && !tabType.equals("")) {
                                    tabTypeList.add(tabType);       //过滤规则列表
                                }

                                //列表去重
                                tabTypeList = new ArrayList<String>(new HashSet<String>(tabTypeList));

                                for (int i = 0; i < tabTypeList.size(); i++) {
                                    dlist=new ArrayList<DownLoadFileInfo>();
                                    String tabType = tabTypeList.get(i);
                                    String[] stringArr = tabType.split(",");
                                    List<String> list = Arrays.asList(stringArr); //某一次过滤的文件类型列表

                                    for (int j = 0; j < list.size(); j++) {
                                        for (int a = 0; a < fileInfoList.size(); a++) {
                                            String fileType = list.get(j);
                                            String fileInfoType = fileInfoList.get(a).getCategoryName();
                                            if (fileType.contains(fileInfoType)) {
                                                dlist.add(fileInfoList.get(a));
                                            }
                                        }
                                    }
                                    tableViewList.get(i).getItems().clear();
                                    tableViewList.get(i).getItems().addAll(dlist);
                                    tabList.get(i).setContent(tableViewList.get(i));
                                }

                                //tableView.getItems().clear();
                                //tableView.getItems().addAll(fileInfo);
                                //tableViewList.add(tableView);

                            }
                        }else{
                            ArrayList<DownLoadFileInfo> fileInfoList = (ArrayList<DownLoadFileInfo>) fileInfo;
                            for (int i = 0; i < tabTypeList.size(); i++) {
                                dlist=new ArrayList<DownLoadFileInfo>();
                                String tabType = tabTypeList.get(i);
                                String[] stringArr = tabType.split(",");
                                List<String> list = Arrays.asList(stringArr); //某一次过滤的文件类型列表

                                for (int j = 0; j < list.size(); j++) {
                                    for (int a = 0; a < fileInfoList.size(); a++) {
                                        String fileType = list.get(j);
                                        String fileInfoType = fileInfoList.get(a).getCategoryName();
                                        if (fileType.contains(fileInfoType)) {
                                            dlist.add(fileInfoList.get(a));
                                        }
                                    }
                                }
                                tableViewList.get(i).getItems().clear();
                                tableViewList.get(i).getItems().addAll(dlist);
                                tabList.get(i).setContent(tableViewList.get(i));
                            }
                        }
                    }
                });
            }

            @Override

            public void changed() {
                Platform.runLater(new Runnable() {
                    public void run() {
                    }
                });
            }

            //下载历史,展示最近一天下载信息
            @Override
            public void downloadHistory(final Collection<DownLoadFileInfo> downloadHistory) {
                Platform.runLater(new Runnable() {
                    public void run() {
                    }
                });
            }
        });
        loadServer.start();
    }

    private void initView() {
        HBox hb = new HBox();
        hb.setPrefHeight(50);
        hb.setSpacing(10);
        hb.setFillHeight(true);

        Label title = new Label("   数据下载监控系统: v 1.0.4   ");
        title.setFont(new Font("Arial", 20));
        MenuBar menuBar=new MenuBar();
        menuBar.setMaxSize(60,50);
        Menu menu=new Menu("菜单");
        menuItem=new MenuItem("新建下载");
        menu.getItems().addAll(menuItem);
        menuBar.getMenus().addAll(menu);

        menuItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                DownloadConfig downloadConfig = new DownloadConfig();
                downloadConfig.show();
            }
        });

        VBox vbox1=new VBox();
        vbox1.setPrefWidth(500);
        vbox1.getChildren().addAll(title,menuBar);

        Label startTime = new Label("启动时间 : "+getTime()+"    ");
        startTime.setFont(new Font("Arial", 20));

        nowTime = new Label("当前时间 : "+getTime()+"    ");
        nowTime.setFont(new Font("Arial", 20));

        VBox vbox2=new VBox();
        vbox2.setPrefWidth(350);
        vbox2.getChildren().addAll(startTime,nowTime);

        taskNum=new Label("等待下载 : ");
        taskNum.setFont(new Font("Arial", 20));

        historyNum=new Label("下载完成 : ");
        historyNum.setFont(new Font("Arial", 20));

        VBox vbox3=new VBox();
        vbox3.setPrefWidth(200);
        vbox3.getChildren().addAll(taskNum,historyNum);

        networkStatus=new Label("网络状态："); //网络状态
        networkStatus.setFont(new Font("Arial", 20));

        dlDestStatus=new Label("下载目录状态： "+"正常"); //下载目标目录状态
        dlDestStatus.setFont(new Font("Arial", 20));

        VBox vbox4=new VBox();
        vbox4.setPrefWidth(200);
        vbox4.getChildren().addAll(networkStatus,dlDestStatus);

        hb.getChildren().addAll(vbox1,vbox2,vbox3,vbox4);
        VBox hBox = new VBox(10);
        //nowTime.setPrefHeight(30);
        //hb.getChildren().add(nowTime);

        Label labelLog=new Label("系统日志");
        labelLog.setFont(new Font("Arial", 20));
        labelLog.setWrapText(true);
        textArea=new TextArea("程序已启动..."+getTime()+"\r\n");
        textArea.setEditable(false);
        textArea.setMinHeight(200);
        textArea.setPrefRowCount(10);
        hBox.getChildren().addAll(labelLog, textArea);

        initTable();    //初始化表

        currDL.setClosable(false);
        hisDL.setClosable(false);
        //dlInfos.getTabs().add(currDL);
        currDL.setContent(currTableView);
        dlInfos.getTabs().add(hisDL);
        hisDL.setContent(hisTableView);

        hb.setStyle("-fx-background-color: aliceblue");
        rootPane.setTop(hb);
        rootPane.setCenter(dlInfos);
        rootPane.setBottom(hBox);

    }

    //初始化表
    private void initTable() {
        currTableView = new TableView();
        currTableView.setEditable(true);

        currTableView.getColumns().addAll(
                getTableColumn("文件类型", "categoryName", 100),
                getTableColumn("文件名称", "fileName", 190),
                getTableColumn("优先级", "filePriority", 100),
                getTableColumnProperty("下载状态", "stateDescP", 150),
                getTableColumnProperty("下载进度", "loadProgressP", 150),
                getTableColumn("生成时间", "createdTimeDesc", 150),
                getTableColumnProperty("开始时间", "startTimeP", 150),
                getTableColumn("下载路径", "url", 400),
                getTableColumnProperty("备注", "errorDescP", 100));

        hisTableView = new TableView();
        hisTableView.setEditable(true);

        hisTableView.getColumns().addAll(
                getTableColumn("文件类型", "categoryName", 100),
                getTableColumn("文件名称", "fileName", 190),
                getTableColumn("优先级", "filePriority", 100),
                getTableColumn("下载状态", "stateDesc", 150),
                getTableColumn("下载进度", "loadProgress", 150),
                getTableColumn("生成时间", "createdTimeDesc", 150),
                getTableColumn("开始时间", "startDownLoadTimeDesc", 150),
                getTableColumn("下载路径", "url", 400),
                getTableColumn("备注", "errorDesc", 100));

    }

    private TableColumn<DownLoadFileInfo, String> getTableColumn(String display, String beanName, double width) {
        TableColumn<DownLoadFileInfo, String> column = new TableColumn<DownLoadFileInfo, String>(display);
        column.setPrefWidth(width);
        column.setCellValueFactory(new PropertyValueFactory<DownLoadFileInfo, String>(beanName));
        return column;
    }

    private TableColumn<DownLoadFileInfo, SimpleStringProperty> getTableColumnProperty(String display, String beanName, double width) {
        TableColumn<DownLoadFileInfo, SimpleStringProperty> column = new TableColumn<DownLoadFileInfo, SimpleStringProperty>(display);
        column.setPrefWidth(width);
        column.setCellValueFactory(new PropertyValueFactory<DownLoadFileInfo, SimpleStringProperty>(beanName));
        return column;
    }

    private String getTime(){
        Date date=new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

     //timer task 每秒更新一次当前时间
    private void updateTime() {
        tmr = new Timer();
        tmr.scheduleAtFixedRate(new JLabelTimerTask(), new Date(), 1000);
    }

    //Timer task 更新当前时间显示
    protected class JLabelTimerTask extends TimerTask {
        @Override
        public void run() {
            Platform.runLater(new Runnable() {
                public void run() {
                    nowTime.setText("当前时间 : "+ getTime());
                }
            });
        }
    }

    @Subscribe
    public void onMessage(Object o){

        if(o instanceof List){
            downLoadHistoryList= (List<DownLoadFileInfo>) o;
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    hisTableView.getItems().clear();
                    hisTableView.getItems().addAll(downLoadHistoryList);
                    historyNum.setText("下载完成 : " + hisTableView.getItems().size());
                    downLoadHistoryList.clear();
                }
            });
        }
        else{
            final String status=o.toString();
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    if(status.equals("0")){
                        networkStatus.setText("网络状态："+"正常");
                        networkStatus.setTextFill(Color.web("BLACK"));
                    }
                    else{
                        networkStatus.setText("网络状态：" + "异常");
                        networkStatus.setTextFill(Color.web("RED"));
                    }
                }
            });
        }
    }

    //timer task 定期查询下载历史列表
    private void searchHistory(EventBus eb){

        SearchHistory sh=new SearchHistory(dbFileName,eb);
        Thread t=new Thread(sh);
        t.start();

    }


    private void updateNetwork(EventBus eb){

        NetWorkMonitor nm=new NetWorkMonitor(eb);
        Thread t=new Thread(nm);
        t.start();
    }

    // 定期清空下载历史列表
    private void cleanHistory() {
        tmr = new Timer();
        tmr.scheduleAtFixedRate(new CleanHistoryTimerTask(), new Date(), 1000*60*20);
    }
    //定期清空下载历史列表
    protected class CleanHistoryTimerTask extends TimerTask {
        @Override
        public void run() {
            Platform.runLater(new Runnable() {
                public void run() {
                    cleanHistoryList();
                }
            });
        }
    }

    //清空下载历史:
    public void cleanHistoryList(){
//        System.out.println("清空下载历史任务执行...");
        sqliteAccess=new SqliteAccess();
        sqliteAccess.connect();

        //currentfile表保存当天数据
        String sql1="DELETE FROM currentfile WHERE  date(createtime)< date('now')";

        //historyfile 表保存最近七天数据
        String sql2="DELETE FROM historyfile  WHERE  date(createtime)< date('now','-7 day')";

        sqliteAccess.deleteHistory(sql1);
        sqliteAccess.deleteHistory(sql2);

        sqliteAccess.disconn();
    }

    public boolean testTab(String tabType){
        for(int i=0;i<tabTypeList.size();i++){
            if(tabTypeList.get(i).contains(tabType)){
                return true;
            }
        }
        return false;
    }

}
